package com.bawei.module_detail.ui

import android.app.AlertDialog
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_mvi.base.BaseMVIActivity
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_detail.R
import com.bawei.module_detail.adapter.CommentAdapter
import com.bawei.module_detail.adapter.TabAdapter
import com.bawei.module_detail.databinding.ActivityPlayBinding
import com.bawei.module_detail.intent.VideoDetailIntent
import com.bawei.module_detail.model.entity.BulletEntityItem
import com.bawei.module_detail.model.entity.LikeCollectBody
import com.bawei.module_detail.model.entity.MovieEntityItem
import com.bawei.module_detail.model.entity.SendBulletBody
import com.bawei.module_detail.state.VideoDetailState
import com.bawei.module_detail.viewmodel.VideoDetailViewModel
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import kotlinx.coroutines.launch
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Duration
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import kotlin.random.Random

private const val TAG = "PlayActivity"

@Route(path = Router.Ui.VIDEO_PLAY_DETAIL)
class PlayActivity : BaseMVIActivity() {
    lateinit var tabAdapter: TabAdapter
    val commentAdapter = CommentAdapter()
    private var list = arrayListOf<Fragment>()
    private var title = arrayListOf<String>()
    private var check = true
    var text = ""
    var isStarted: Boolean = false
    val danmakuContext = DanmakuContext.create()

    // 弹幕数据列表
    private val bulletList = mutableListOf<BulletEntityItem>()

    // 是否正在循环播放弹幕
    private var isLooping = false

    // 定时器
    private val handler = Handler(Looper.getMainLooper())

    // 弹幕间隔时间(毫秒)
    private val DANMAKU_INTERVAL = 1000L

    @Autowired(name = "movie")
    lateinit var videoEntity: MovieEntityItem
    private lateinit var videoDetailViewModel: VideoDetailViewModel
    private val binding: ActivityPlayBinding by lazy {
        ActivityPlayBinding.inflate(layoutInflater)
    }

    private val client = OkHttpClient()
    private var webSocket: WebSocket? = null
    private var reconnectAttempts = 0
    private val maxReconnectAttempts = 5
    private var isManualClose = false
    private var hasLike = 0
    private var hasCollection = 0

    private class SafeWebSocketListener(
        private val activityRef: WeakReference<PlayActivity>
    ) : WebSocketListener() {

        override fun onOpen(webSocket: WebSocket, response: Response) {
            val activity = activityRef.get()
            activity?.let {
                it.reconnectAttempts = 0
                // 安全调用 webSocket（可能为 null）
                it.webSocket?.send("Hello Server!")
                Log.d("WebSocket", "连接成功")
            }
        }

        override fun onMessage(webSocket: WebSocket, text: String) {
            val activity = activityRef.get()
            activity?.let {
                Log.d("WebSocket", "Received text: $text")
                // 处理弹幕逻辑（根据需求补充）
            }
        }

        override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            val activity = activityRef.get()
            activity?.let {
                Log.d("WebSocket", "连接关闭: $reason")
            }
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            val activity = activityRef.get()
            activity?.let {
                Log.e("WebSocket", "Error: ${t?.message ?: "未知错误"}")
            }
        }
    }

    override fun generateViewModel() {
        videoDetailViewModel = ViewModelProvider(this)[VideoDetailViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun initView() {
        super.initView()
        ARouter.getInstance().inject(this)
        initVideoDetail()
        initLoveIcon()
        initCollectionIcon()
//        connect("ws://10.161.9.80:7015/api/danmu/websocket/${"6936590061114753549"}")
    }

    private fun initCollectionIcon() {
        if (AuthMMKV.hasCollection == 1) {
            binding.detailVideoCollection.setImageResource(R.drawable.baseline_star_24)
        } else {
            binding.detailVideoCollection.setImageResource(R.drawable.ic_star_24)
        }
    }

    private fun initLoveIcon() {
        if (AuthMMKV.hasLike == 1) {
            binding.detailVideoLove.setImageResource(com.bawei.lib_common.R.drawable.ic_love_25)
        } else {
            binding.detailVideoLove.setImageResource(com.bawei.lib_common.R.drawable.ic_love_24)
        }
    }

    // 启动WebSocket连接
    fun connect(url: String) {
        isManualClose = false
        // 先关闭旧连接
        webSocket?.close(1000, "Reconnect")
        val request = Request.Builder().url(url).build()
        webSocket = client.newWebSocket(
            request,
            SafeWebSocketListener(
                WeakReference(this)
            )
        )
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            videoDetailViewModel.intents.send(
                VideoDetailIntent.getCommentByUserId(
                    0,
                    "7046705001120399908"
                )
            )
        }
        lifecycleScope.launch {
            videoDetailViewModel.intents.send(VideoDetailIntent.getBullet(0, "6936590061114753549"))
        }
        binding.linearLayout.setOnClickListener {
            showDanmakuSendDialog()
        }
        binding.detailVideoLove.setOnClickListener {
            val body = LikeCollectBody(
                ctime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()),
                id = 0,
                itemcode = "6936590061114753549".toLong(),
                userid = AuthMMKV.uId,
                sourceflag = 0,
                verifycode = "aaabbb"
            )
            if (hasLike == 0) {
                // 乐观更新
                hasLike = 1
                updateLoveIcon()
                lifecycleScope.launch {
                    videoDetailViewModel.intents.send(VideoDetailIntent.agreeVideo(body))
                }
            } else if (hasLike == 1) {
                // 乐观更新
                hasLike = 0
                updateLoveIcon()
                lifecycleScope.launch {
                    videoDetailViewModel.intents.send(VideoDetailIntent.cancelAgreeVideo(body))
                }
                ToastUtils.showLong("取消点赞成功")
            }
        }
        binding.detailVideoCollection.setOnClickListener {
            val body = LikeCollectBody(
                ctime = "${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())}",
                id = 0,
                itemcode = "6936590061114753549".toLong(),
                userid = AuthMMKV.uId,
                sourceflag = 0,
                verifycode = "aaabbb"
            )
            if (hasCollection == 0) {
                hasCollection = 1
                updateCollectionIcon()
                lifecycleScope.launch {
                    videoDetailViewModel.intents.send(VideoDetailIntent.collectVideo(body))
                }
            } else {
                hasCollection = 0
                updateCollectionIcon()
                lifecycleScope.launch {
                    videoDetailViewModel.intents.send(VideoDetailIntent.cancelCollectVideo(body))
                }
                ToastUtils.showLong("取消收藏成功")
            }
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoCommentFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.VideoCommentSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            commentAdapter.setCommentData(it.list!!)
                            list.add(ProfileFragment())
                            list.add(CommentsFragment())
                            title.add("简介")
                            title.add("评论(${commentAdapter.getSize()})")
                            tabAdapter = TabAdapter(
                                supportFragmentManager,
                                FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
                                list,
                                title
                            )
                            binding.detailVideoVp.adapter = tabAdapter
                            binding.detailVideoTab.setupWithViewPager(binding.detailVideoVp)
                            commentAdapter.notifyDataSetChanged()

                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoDetailBulletFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.GetBulletSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            receiveBulletData(it.list!!)
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoDetailSendBulletFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.SendBulletSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            ToastUtils.showLong("发送弹幕成功")
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoDetailLoveFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.AgreeVideoSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            AuthMMKV.hasLike = 1
                            updateLoveIcon()
                            ToastUtils.showLong("点赞成功")
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoDetailNoLoveFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.CancelAgreeVideoSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            AuthMMKV.hasLike = 0
                            updateLoveIcon()
                            ToastUtils.showLong("取消点赞成功")
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoDetailStarFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.CollectVideoSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            AuthMMKV.hasCollection = 1
                            updateCollectionIcon()
                            ToastUtils.showLong("收藏成功")
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._simpleVideoDetailNoStarFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.CancelCollectVideoSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            AuthMMKV.hasCollection = 0
                            updateCollectionIcon()
                            ToastUtils.showLong("取消收藏成功")
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
    }

    // 添加单条弹幕
    private fun addDanmaku(data: BulletEntityItem?) {

        val danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        // 关键修复：检查是否为 null
        if (danmaku == null) {
            Log.e("Danmaku", "Failed to create danmaku object")
            return
        }
        danmaku.apply {
            text = data?.content;
            //设置相应的边距，这个设置的是四周的边距
            padding = 5;
            // 可能会被各种过滤器过滤并隐藏显示，若果是本机发送的弹幕，建议设置成1；
            //priority = 0;
            //设置文字大小
            textSize = 50f;
            //设置文字颜色
            textColor = Color.WHITE;
            //设置阴影的颜色
//                    textShadowColor = Color.WHITE;
            //设置线颜色
//                    underlineColor = Color.WHITE;
            //设置背景颜色
//                borderColor = Color.WHITE;
            duration = Duration(Random.nextLong(3000, 4000))
            time = binding.detailVideoDanma.currentTime
        }
        binding.detailVideoDanma.addDanmaku(danmaku)
        // 首次添加弹幕时启动
        if (!isStarted) {
            binding.detailVideoDanma.start()
            isStarted = true
        }
    }

    fun receiveBulletData(data: List<BulletEntityItem>) {
        bulletList.clear()
        bulletList.addAll(data)
        //如果还没有开始循环，启动循环
        if (!isLooping) {
            startDanmakuLoop()
        }
    }

    //开始循环播放弹幕
    private fun startDanmakuLoop() {
        isLooping = true
        var index = 0
        handler.post(object : Runnable {
            override fun run() {
                if (bulletList.isNotEmpty() && binding.detailVideoDanma.isShown) {
                    //获取当前的弹幕
                    val data = bulletList[index]
                    addDanmaku(data)
                    //更新索引，继续播放
                    index = (index + 1) % bulletList.size
                }
                //继续下一个弹幕
                handler.postDelayed(this, DANMAKU_INTERVAL)
            }

        })
    }

    private fun initVideoDetail() {
        //标题
        binding.detailVideoTitle.text = videoEntity.description
        //返回
        binding.detailVideoBack.setOnClickListener {
            finish()
        }

        binding.detailPlayer.setUp(videoEntity.videopath, false, null)
        //视频播放
        binding.detailPlayer.startPlayLogic()
        binding.detailPlayer.backButton.visibility = View.GONE
        //头像
        Glide.with(this).load(videoEntity.avatar_url).circleCrop()
            .into(binding.detailVideoHeard)
        //用户名
        binding.detailVideoAuthor.text = videoEntity.name
//        binding.detailVideoShareDesc.setOnClickListener {
//            val web: UMWeb = UMWeb(simpleVideoEntity.videopath)
//            web.title = simpleVideoEntity.title //标题
//            web.setThumb(UMImage(this, simpleVideoEntity.videomainimag)) //缩略图
//            web.description = simpleVideoEntity.name //描述
//            ShareAction(this)
//                .withMedia(web)
//                .open()
//        }
    }

    /**
     * 显示弹幕发送对话框
     */
    private fun showDanmakuSendDialog() {
        val dialog = AlertDialog.Builder(this)
            .create()

        val dialogView = layoutInflater.inflate(R.layout.dialog_danmaku_send, null)
        dialog.setView(dialogView)

        val etContent = dialogView.findViewById<EditText>(R.id.et_danmaku_content)
        val tvCharCount = dialogView.findViewById<TextView>(R.id.tv_char_count)
        val btnSend = dialogView.findViewById<Button>(R.id.btn_send_danmaku)
        val ivClose = dialogView.findViewById<ImageView>(R.id.iv_close)

        // 监听输入内容变化，更新字符计数
        etContent.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                val length = s?.length ?: 0
                tvCharCount.text = "$length/50"

                // 根据输入长度改变按钮状态
                btnSend.isEnabled = length > 0
                btnSend.alpha = if (length > 0) 1.0f else 0.5f
            }
        })

        // 发送弹幕按钮点击事件
        btnSend.setOnClickListener {
            val content = etContent.text.toString().trim()
            if (content.isNotEmpty()) {
                sendDanmaku(content)
                dialog.dismiss()
//                ToastUtils.showShort(this@VideoDetailActivity, "弹幕发送成功")
            } else {
                ToastUtils.showShort("请输入弹幕内容")
            }
        }

        // 关闭按钮点击事件
        ivClose.setOnClickListener {
            dialog.dismiss()
        }

        // 设置对话框属性
        dialog.window?.apply {
            setBackgroundDrawableResource(android.R.color.transparent)
            setLayout(
                (resources.displayMetrics.widthPixels * 0.9).toInt(),
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }

        dialog.show()
    }

    /**
     * 发送弹幕
     */
    private fun sendDanmaku(content: String) {
        // 创建弹幕对象
        val danmaku =
            danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
                text = content
                padding = 5
                textSize = 50f
                textColor = Color.WHITE
                duration = Duration(Random.nextLong(3000, 4000))
                time = binding.detailVideoDanma.currentTime
            }

        // 添加弹幕到屏幕
        binding.detailVideoDanma.addDanmaku(danmaku)

        // 如果弹幕还没开始播放，则开始播放
        if (!isStarted) {
            binding.detailVideoDanma.start()
            isStarted = true
        }
        val sendBulletBody = SendBulletBody(
            content = content,
            createtime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()),
            datatype = 0,
            fontcolor = "#FFFFFF",
            fontsize = 50,
            id = 0,
            itemid = "6936590061114753549".toLong(),
            userid = AuthMMKV.uId
        )

        // 通过WebSocket发送弹幕到服务器
//        webSocket?.send(Gson().toJson(sendBulletBody))
        lifecycleScope.launch {
            LoggerUtils.d("WebSocket", "发送弹幕: $content")
            videoDetailViewModel.intents.send(VideoDetailIntent.sendBullet(sendBulletBody))
        }
    }

    private fun updateLoveIcon() {
        if (hasLike == 1) {
            binding.detailVideoLove.setImageResource(com.bawei.lib_common.R.drawable.ic_love_25)
        } else {
            binding.detailVideoLove.setImageResource(com.bawei.lib_common.R.drawable.ic_love_24)
        }
    }

    private fun updateCollectionIcon() {
        if (hasCollection == 1) {
            binding.detailVideoCollection.setImageResource(R.drawable.baseline_star_24)
        } else {
            binding.detailVideoCollection.setImageResource(R.drawable.ic_star_24)
        }
    }

    // 尝试重连
    private fun tryReconnect(url: String) {
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++
            binding.root.postDelayed({ connect(url) }, 2000L)
        } else {
            Log.e("WebSocket", "重连次数过多，已停止重连")
        }
    }

    // 关闭连接
    fun disconnect() {
        isManualClose = true
        webSocket?.close(1000, "User disconnect")
        webSocket = null
    }

    override fun onPause() {
        super.onPause()
        binding.detailVideoDanma.pause()
        binding.detailPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        binding.detailPlayer.onVideoResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.detailVideoDanma.release()
        binding.detailPlayer.release()
        isLooping = false
        handler.removeCallbacksAndMessages(null)
        disconnect()
    }

}